/*
    Copyright 2012 Peter Pratscher

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using LicenseAdder.Model;
using LicenseAdder.Properties;

namespace LicenseAdder
{
    public partial class MainForm : Form
    {
        List<string> filesToProcess = new List<string>();
        List<string> filesProcessed = new List<string>();
        List<string> filesProcessedWithError = new List<string>();
        string _CustomPattern, _CustomStartTag, _CustomEndTag;
        public MainForm()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(tbxRootFolder.Text))
            {
                folderBrowser.SelectedPath = tbxRootFolder.Text;
            }

            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                tbxRootFolder.Text = folderBrowser.SelectedPath;
            }
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbxLicenseText.Text))
            {
                MessageBox.Show("Please enter a license text!", "License Adder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(tbxRootFolder.Text))
            {
                MessageBox.Show("Please select the root folder to process!", "License Adder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!chxCSharpFiles.Checked && !chxJavaFiles.Checked && !chxVisualBasic.Checked && !chxXmlFiles.Checked && !chxPHPFiles.Checked && !chxPythonFiles.Checked && !chxRubyFiles.Checked && !chxHTMLFiles.Checked && !chxJavaScriptFiles.Checked && !chxOther.Checked)
            {
                MessageBox.Show("Please select at least one file type to process!", "License Adder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            filesToProcess.Clear();

            SearchOption option;

            if (chxIncludeSubFolders.Checked)
            {
                option = SearchOption.AllDirectories;
            }
            else
            {
                option = SearchOption.TopDirectoryOnly;
            }

            if (chxCSharpFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.cs", option));
            }
            if (chxJavaFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.java", option));
            }
            if (chxVisualBasic.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.vb", option));
            }
            if (chxXmlFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.xml", option));
            }
            if (chxHTMLFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.html", option));
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.htm", option));
            }
            if (chxJavaScriptFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.js", option));
            }
            if (chxPHPFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.php", option));
            }
            if (chxPythonFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.py", option));
            }
            if (chxRubyFiles.Checked)
            {
                filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, "*.rb", option));
            }
            if (chxOther.Checked)
            {
                if (!string.IsNullOrEmpty(tbxPattern.Text) && !string.IsNullOrEmpty(tbxStartTag.Text) && !string.IsNullOrEmpty(tbxEndTag.Text))
                {
                    filesToProcess.AddRange(Directory.GetFiles(tbxRootFolder.Text, tbxPattern.Text, option));
                    _CustomPattern = tbxPattern.Text;
                    _CustomStartTag = tbxStartTag.Text;
                    _CustomEndTag = tbxEndTag.Text;
                }
                else
                {
                    MessageBox.Show("No pattern or start / end tag specified!", "License Adder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            if (filesToProcess.Count == 0)
            {
                MessageBox.Show("No files were found in the selected directory!", "License Adder", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            ConfirmFilesForm frm = new ConfirmFilesForm();
            frm.lstFiles.Items.AddRange(filesToProcess.ToArray());

            if (frm.ShowDialog() != DialogResult.OK) return;

            filesProcessed.Clear();
            filesProcessedWithError.Clear();

            btnProcess.Text = "Processing...";
            btnProcess.Enabled = false;
            gpSettings.Enabled = false;
            gbLicenseText.Enabled = false;

            progressBar.Value = 0;
            worker.RunWorkerAsync(new List<string>(tbxLicenseText.Lines));
        }

        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            string fileExtension;
            string fileName;
            List<string> licenseText = (List<string>)e.Argument;

            for (int i = 0; i < filesToProcess.Count; i++)
            {
                fileName = filesToProcess[i];

                try
                {
                    fileExtension = Path.GetExtension(fileName);

                    switch (fileExtension)
                    {
                        case ".cs":
                        case ".java":
                        case ".php":
                        case ".js":
                            CSJavaLicenseAdder.ProcessFile(fileName, licenseText);
                            break;

                        case ".xml": 
                        case ".html": 
                        case ".htm":
                            XmlLicenseAdder.ProcessFile(fileName, licenseText);
                            break;

                        case ".vb":
                            VbLicenseAdder.ProcessFile(fileName, licenseText);
                            break;
                        case ".rb":
                            RubyLicenseAdder.ProcessFile(fileName, licenseText);
                            break;
                        case ".py":
                            PythonLicenseAdder.ProcessFile(fileName, licenseText);
                            break;
                        default:
                            CustomLicenseAdder.ProcessFile(fileName, _CustomStartTag, _CustomEndTag, licenseText);
                            break;
                    }

                    filesProcessed.Add(fileName);
                }
                catch (Exception ex)
                {
                    filesProcessedWithError.Add(ex.ToString());
                }

                if (i % 1 == 0)
                {
                    worker.ReportProgress(i * 100 / filesToProcess.Count);
                }
            }
        }

        private void worker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
        }

        private void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            progressBar.Value = 100;

            ProcessCompletedForm frm = new ProcessCompletedForm();

            if (filesProcessed.Count > 0)
                frm.lstSuccess.Items.AddRange(filesProcessed.ToArray());

            if (filesProcessedWithError.Count > 0)
                frm.lstError.Items.AddRange(filesProcessedWithError.ToArray());

            frm.ShowDialog();

            btnProcess.Text = "Process";
            btnProcess.Enabled = true;
            gpSettings.Enabled = true;
            gbLicenseText.Enabled = true;
        }

        private void cbxTemplates_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxTemplates.SelectedIndex == 0)
                tbxLicenseText.Text = Resources.Apache_2_0_Template;
            if (cbxTemplates.SelectedIndex == 1)
                tbxLicenseText.Text = Resources.GPL_3_Template;
            if (cbxTemplates.SelectedIndex == 2)
                tbxLicenseText.Text = Resources.GPL_2_Template;
            if (cbxTemplates.SelectedIndex == 3)
                tbxLicenseText.Text = Resources.BSD_License;
            if (cbxTemplates.SelectedIndex == 4)
                tbxLicenseText.Text = Resources.MIT_License;
            if (cbxTemplates.SelectedIndex == 5)
                tbxLicenseText.Text = Resources.Mozilla_Public_License_1_1;
        }
    }
}
